<template>
  <div class="container">
    <div class="cheader2">
      <van-icon
          @click="goBack"
          class="chl"
          name="arrow-left"
          color="#000"
          size="20"
      />
      <div class="chtitle">{{ $t('all.tixian') }}</div>
      <div class="djbox"></div>
    </div>

    <div class="mbox">
      <!-- 选择货币类型 -->
      <div class="bbtn" @click="showLegalTenderOption = true">
        <img class="bb1" :src="getLegalTenderIconByCode(legalTenderSelection.code)" alt=""/>
        <span class="bb2">{{ legalTenderSelection.code }}</span>
        <van-icon color="#000" name="arrow-down"/>
      </div>

      <!--    <div class="ibox1">
            <img src="@/assets/images/usdt.png" alt="" />
            &lt;!&ndash; <div>Unity Swap</div> &ndash;&gt;
          </div>-->
      <!-- USDT提现 -->
      <div class="ibox2" v-show="legalTenderSelection.code === 'USDT'">
        <div class="ili">
          <div class="ili-1">{{ $t('all.dizhi') }}</div>
          <div class="ili-2">
            <van-field
                v-model="submitForm.address"
                :placeholder="$t('all.dizhitip')"
            />
          </div>
        </div>
        <div class="ili">
          <div class="ili-1">{{ $t('all.tixianshuliang') }}</div>
          <div class="ili-2">
            <van-field
                v-model="submitForm.amount"
                placeholder="0"
                :border="false"
            />
            <span class="xxx">USDT <span @click="chooseAll">{{ $t('all.quanbu') }}</span></span>
          </div>
        </div>
        <div class="ali">
          <div class="ali1">{{ $t('all.keyongzichan') }}</div>
          <div class="ali2">{{ infos?.balance }} USDT</div>
        </div>
        <div class="ali">
          <div class="ali1">{{ $t('all.zuixiaotixianjine') }}</div>
          <div class="ali2">
            {{ item.minimumWithdrawalAmount }} USDT
          </div>
        </div>
        <div class="ali">
          <div class="ali1">{{ $t('all.shouxufei') }}</div>
          <div class="ali2">{{ item.serviceCharge }} USDT</div>
        </div>

        <div class="btn" @click="handleSubmit">{{ $t('all.tijiao') }}</div>
      </div>

      <!-- 法币提现 -->
      <div class="ibox2" v-show="legalTenderSelection.code !== 'USDT'">
        <!-- 渠道 -->
        <div class="ili">
          <div class="ili-1">{{ $t('all.withdrawalChannel') }}</div>
          <div class="ili-2">
            <van-field
                @click="showQGPayBusinessOption = true"
                readonly
                v-model="legalTenderWithdrawalForm.businessName"
                :placeholder="$t('all.click2ChoseWithdrawalChannel')"
            />
          </div>
        </div>
        <!-- 提现金额 -->
        <div class="ili">
          <div class="ili-1">{{ $t('all.withdrawalAmount') }}</div>
          <div class="ili-2">
            <van-field
                v-model="legalTenderWithdrawalForm.amount"
                :placeholder="`${$t('all.amountLimit')}：${qGPayBusinessSelection ? qGPayBusinessSelection.minAmount + ' - ' + qGPayBusinessSelection.maxAmount : $t('all.noRechargeChannelSelected')}`"
            />
          </div>
          <div class="m5">{{ `≈ ${legalTender2USDT} USDT` }}</div>
        </div>
        <!-- 银行 -->
        <div class="ili" v-show="qGPayBankOption.length > 0">
          <div class="ili-1">{{ $t('all.bank') }}</div>
          <div class="ili-2">
            <van-field
                @click="showQGPayBankOption = true"
                readonly
                v-model="legalTenderWithdrawalForm.bankName"
                :placeholder="$t('all.click2ChoseBank')"
            />
          </div>
        </div>
        <!-- 账号 -->
        <div class="ili">
          <div class="ili-1">{{ $t('all.account') }}</div>
          <div class="ili-2">
            <van-field
                v-model="legalTenderWithdrawalForm.account"
                :placeholder="$t('all.account')"
            />
          </div>
        </div>
        <!-- 账户名 -->
        <div class="ili">
          <div class="ili-1">{{ $t('all.accountName') }}</div>
          <div class="ili-2">
            <van-field
                v-model="legalTenderWithdrawalForm.accountName"
                :placeholder="$t('all.accountName')"
            />
          </div>
        </div>
        <div class="ali">
          <div class="ali1">{{ $t('all.keyongzichan') }}</div>
          <div class="ali2">{{ infos?.balance }} USDT</div>
        </div>
        <div class="ali">
          <div class="ali1">{{ $t('all.zuixiaotixianjine') }}</div>
          <div class="ali2">
            1 USDT
          </div>
        </div>
        <div class="ali">
          <div class="ali1">{{ $t('all.shouxufei') }}</div>
          <div class="ali2">{{ legalTenderFee }} USDT</div>
        </div>
        <!-- 提示 -->
        <div class="m5" v-show="legalTenderSelection.code !== 'USDT'">
          {{ $t('all.legalTenderWithdrawalTips1') }}
        </div>

        <div class="ili" style="height: 38px">
          <div class="btn" @click="submitLegalTenderWithdrawal">
            {{ legalTenderWithdrawalSubmit ? $t('all.processing') : $t('all.tijiao') }}
          </div>
        </div>
      </div>
    </div>

    <!-- 选择货币类型 -->
    <van-dialog
        v-model:show="showLegalTenderOption"
        :title="$t('all.choseLegalTender')"
        :confirmButtonText="$t('all.queren')"
        style="overflow: auto;"
        :closeOnClickOverlay="true"
    >
      <div class="cli" @click="selectLegalTender(i)" v-for="i in legalTenderOption" :key="i.code">
        <img :style="legalTenderSelection.code === 'USDT' ? '' : 'border-radius: 0px'"
             :src="getLegalTenderIconByCode(i.code)" alt=""/>
        <div class="cli2">{{ i.code }}</div>
      </div>
    </van-dialog>

    <!-- 选择业务编码 -->
    <van-dialog
        v-model:show="showQGPayBusinessOption"
        :title="$t('all.choseQGPayChannel')"
        :confirmButtonText="$t('all.queren')"
        style="overflow: auto;"
        :closeOnClickOverlay="true"
    >
      <div class="cli" @click="selectQGPayBusiness(i)" v-for="i in qGPayBusinessOption" :key="i.code">
        <div class="cli2" style="width: 100%;">{{ i.name }}</div>
      </div>
    </van-dialog>

    <!-- 选择银行 -->
    <van-dialog
        v-model:show="showQGPayBankOption"
        :title="$t('all.bank')"
        :confirmButtonText="$t('all.queren')"
        style="height: 50%;overflow: auto;"
        :closeOnClickOverlay="true"
    >
      <!-- 根据名称搜索 -->
      <div class="ili">
        <div class="ili-2">
          <van-field
              v-model="bankOptionQueryForm.name"
              :placeholder="$t('all.selectByBankName')"
          >
            <template #button>
              <van-button size="medium" type="primary" @click="resetBankList">{{ $t('all.select') }}</van-button>
            </template>
          </van-field>
        </div>
      </div>

      <van-list
          style="margin-top: 30px; margin-bottom: 30px"
          v-model:loading="bankOptionLoading"
          :finished="bankOptionFinished"
          :finished-text="$t('all.meiyougengduole')"
          @load="getBankList"
          :immediate-check="false"
          :loading-text="$t('all.jiazaizhong')"
      >
        <div class="cli" @click="selectQGPayBank(i)" v-for="i in qGPayBankOption" :key="i.code">
          <div class="cli2" style="width: 100%;">{{ i.name }}</div>
        </div>
      </van-list>
    </van-dialog>
  </div>
</template>

<script setup lang='ts'>
import {computed, getCurrentInstance, onMounted, reactive, ref} from "vue";
import {useRouter} from "vue-router";
import {useStore} from "@/store";
import {Toast} from "vant";
import BigNumber from "bignumber.js";
import {toNonExponential} from "@/utils/common";
import http from "@/utils/http";
import {
  checkQGPayBusinessAmountLimit,
  getLegalTenderIconByCode,
  legalTenderRechargeLanguage
} from "@/utils/legalTenderRechargeUtils";

const {appContext: {config: {globalProperties}}} = getCurrentInstance();

const store = useStore();
const router = useRouter();
const infos = computed(() => store.state.users.infos)
const item = computed(() => infos.value.rechargeAddress.find((v: any) => v.chain === infos.value.envChain))

const submitForm = reactive({
  address: '',
  amount: '',
});

// 法币相关
const legalTenderUSDT = {
  code: 'USDT',
  rate: '1'
}
const showLegalTenderOption = ref(false)
let legalTenderOption: any = []
const legalTenderSelection = ref(legalTenderUSDT)
const legalTender2USDT = computed(() => {
  if (!legalTenderWithdrawalForm.amount || isNaN(legalTenderWithdrawalForm.amount)) {
    return 0
  }

  const amount = new BigNumber(legalTenderWithdrawalForm.amount);
  let num = amount.div(legalTenderSelection.value.rate)
      .dp(8)
      .toNumber()

  return toNonExponential(num)
})
const legalTenderFee = computed(() => {
  if (legalTenderWithdrawalForm.amount === 0 || !infos.value.legalTenderWithdrawalFeeRate) {
    return 0
  }

  const usdt = new BigNumber(legalTender2USDT.value);
  const num = usdt.multipliedBy(new BigNumber(infos.value.legalTenderWithdrawalFeeRate))
  return toNonExponential(num)
})
let legalTenderWithdrawalSubmit = ref(false)
const legalTenderWithdrawalForm: any = reactive({
  legalTenderCode: '',
  amount: '',
  businessName: '',
  businessCode: '',
  bankName: '',
  bankCode: '',
  account: '',
  accountName: '',
  phone: '',
  province: '',
  identityNo: '',
  identityType: ''
})

// 业务编码相关
const showQGPayBusinessOption = ref(false)
const qGPayBusinessOption = ref<any>([])
let qGPayBusinessSelection = ref<any>(undefined)

// 银行相关
const showQGPayBankOption = ref(false)
const qGPayBankOption = ref<any>([])
let qGPayBankSelection = ref<any>(undefined)
const bankOptionQueryForm = reactive({
  name: '',
  businessCode: '',
  pageNum: 1,
  pageSize: 10
})
const bankOptionLoading = ref(false)
const bankOptionFinished = ref(false)

onMounted(() => {
  legalTenderSelection.value = legalTenderUSDT
  legalTenderWithdrawalSubmit.value = false
  selectLegalTenderOption()
});

// 查询法币列表
const selectLegalTenderOption = () => {
  // 第一个永远使用USDT
  legalTenderOption = [legalTenderUSDT]
  http.get("legal-tender/app/list").then((res: any) => {
    if (res.code === 200) {
      legalTenderOption = legalTenderOption.concat(res.rows)
    }
  });
}

// 选择法币
const selectLegalTender = (legalTender: any) => {
  legalTenderSelection.value = legalTender
  if (legalTender.code === 'USDT') {
    showLegalTenderOption.value = false;
    return
  }

  // 如果是法币，根据法币编码查询 代付业务编码
  resetQGPayBusiness();
  resetQGPayBank()
  http.get("qg-pay/business/app/list", {
    legalTenderCode: legalTenderSelection.value.code,
    type: '1'
  }).then((res: any) => {
    if (res.code === 200) {
      // 翻译
      for (let i = 0; i < res.rows.length; i++) {
        let item = res.rows[i];
        item.name = legalTenderRechargeLanguage(globalProperties, item.name);
      }

      qGPayBusinessOption.value = res.rows
    }

    showLegalTenderOption.value = false;
  });
};

// 重置业务编码选项及相关数据
const resetQGPayBusiness = () => {
  qGPayBusinessOption.value = []
  legalTenderWithdrawalForm.businessName = undefined
  legalTenderWithdrawalForm.code = undefined
  qGPayBusinessSelection.value = undefined
}

// 重置银行编码选项及相关数据
const resetQGPayBank = () => {
  qGPayBankOption.value = []
  legalTenderWithdrawalForm.bankName = undefined
  legalTenderWithdrawalForm.bankCode = undefined
  qGPayBankSelection.value = undefined
}

// 选择业务编码
const selectQGPayBusiness = (business: any) => {
  qGPayBusinessSelection.value = business
  legalTenderWithdrawalForm.businessName = business.name
  showQGPayBusinessOption.value = false;

  // 如果是法币，根据代付业务编码查询 银行编码
  resetQGPayBank()
  bankOptionQueryForm.businessCode = qGPayBusinessSelection.value.code
  resetBankList()
};

// 重置银行列表
const resetBankList = () => {
  qGPayBankOption.value = []
  bankOptionQueryForm.pageNum = 0
  bankOptionQueryForm.pageSize = 10
  getBankList()
}

// 查询银行列表
const getBankList = () => {
  bankOptionQueryForm.pageNum += 1
  http.get("qg-pay/bank/app/page", bankOptionQueryForm).then((res: any) => {
    if (res.code === 200) {
      if (!res.rows) {
        qGPayBankOption.value = res.rows
      } else {
        qGPayBankOption.value = qGPayBankOption.value.concat(res.rows)
      }

      bankOptionLoading.value = false
      bankOptionFinished.value = qGPayBankOption.value.length >= res.total
    }

    showQGPayBusinessOption.value = false;
  });
}

// 选择银行编码
const selectQGPayBank = (bank: any) => {
  qGPayBankSelection.value = bank
  legalTenderWithdrawalForm.bankName = bank.name
  showQGPayBankOption.value = false;
};

const submitLegalTenderWithdrawal = () => {
  if (legalTenderWithdrawalSubmit.value) {
    Toast(globalProperties.$t('all.processing'));
    return;
  }

  if (!legalTenderWithdrawalForm.amount || legalTender2USDT.value < 1) {
    Toast(globalProperties.$t('all.theWithdrawalAmountIsIncorrect'));
    return;
  }
  if (!qGPayBusinessSelection.value) {
    Toast(globalProperties.$t('all.noWithdrawalChannelSelected'));
    return;
  }
  if (new BigNumber(legalTender2USDT.value).comparedTo(new BigNumber(infos.value.balance)) > 0) {
    Toast(globalProperties.$t('all.theWithdrawalAmountIsIncorrect'));
    return;
  }
  if (!checkQGPayBusinessAmountLimit(qGPayBusinessSelection, submitForm.amount)) {
    Toast(globalProperties.$t('all.theWithdrawalAmountIsIncorrect'));
    return;
  }
  if (qGPayBankOption.value && qGPayBankOption.value.length > 0 && !qGPayBankSelection.value) {
    Toast(globalProperties.$t('all.noBankSelected'));
    return;
  }

  legalTenderWithdrawalSubmit.value = true
  legalTenderWithdrawalForm.legalTenderCode = legalTenderSelection.value.code
  legalTenderWithdrawalForm.businessCode = qGPayBusinessSelection.value.code
  legalTenderWithdrawalForm.bankCode = qGPayBankSelection.value ? qGPayBankSelection.value.code : undefined
  http.post("qg-pay/withdrawal-detail", legalTenderWithdrawalForm).then((res: any) => {
    if (res.code === 200) {
      resetLegalTenderWithdrawalForm()
    } else {
      Toast(globalProperties.$t('all.operationFailed'));
    }
  }).finally(() => {
    legalTenderWithdrawalSubmit.value = false
  })
}

// 提现法币重置表单
const resetLegalTenderWithdrawalForm = () => {
  legalTenderWithdrawalForm.amount = ''
}


const chooseAll = () => {
  submitForm.amount = infos.value.balance;
};
const handleSubmit = () => {
  if (!submitForm.address) {
    Toast(globalProperties.$t('all.shuaxinchenggong'));
    return;
  }

  if (!submitForm.amount ||
      submitForm.amount > infos.value.balance ||
      submitForm.amount < item.value.minimumWithdrawalAmount
  ) {
    Toast(globalProperties.$t('all.tixianjinebuzhengque'));
    return;
  }
  router.push({
    path: "/capital/confirmwithdrawal",
    query: {
      address: submitForm.address,
      amount: submitForm.amount,
      fee: item.value.serviceCharge,
    },
  });
};
const goBack = () => {
  router.go(-1);
};
</script>

<style lang="scss" scoped>
.cheader2 {
  width: 100%;
  height: 45px;
  background-color: #fff;
  font-size: 16px;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;

  .chl {
    position: absolute;
    left: 16px;
    top: 50%;
    text-align: center;
    transform: translateY(-50%);
  }

  .chtitle {
    position: absolute;
    left: 50%;
    top: 50%;
    text-align: center;
    transform: translate(-50%, -50%);
  }

  .djbox {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;

    img {
      width: 16px;
      margin-right: 4px;
    }

    div {
      font-size: 13px;
      color: #878b97;
    }
  }
}

.ibox1 {
  margin-top: 45px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 140px;

  img {
    width: 60px;
    margin-bottom: 14px;
  }

  div {
    font-size: 13px;
    color: #000;
    text-align: center;
  }
}

.ibox2 {
  margin: 10px 00px;
}

.ili {
  display: flex;
  flex-direction: column;
  margin-bottom: 14px;

  .ili-1 {
    font-size: 12px;
    color: #000;
    margin-bottom: 10px;
  }

  .ili-2 {
    background-color: #2d2f3b;
    border-radius: 4px;
    // height: 38px;
    position: relative;

    .xxx {
      position: absolute;
      right: 14px;
      top: 50%;
      transform: translateY(-50%);
      color: #878b97;
      font-size: 13px;
      z-index: 1001;

      span {
        margin-left: 6px;
        color: #36b4ea;
      }
    }
  }
}

.btn {
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #fff;
  background-image: linear-gradient(to bottom right, #36b4ea, #0996d3);
  border-radius: 3px;
  width: calc(100% - 40px);
  position: fixed;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
}

.ali {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 26px;

  .ali1 {
    font-size: 12px;
    color: #878b97;
  }

  .ali2 {
    color: #000;
    font-size: 12px;
  }
}

.mbox {
  margin-top: 45px;
  padding: 10px 16px;

  .bbtn {
    width: 40vw;
    height: 40px;
    border-radius: 20px;
    background: rgba($color: #fff, $alpha: 1);
    display: flex;
    align-items: center;
    margin: 10px auto 0px;

    .bb1 {
      width: 20px;
      margin: 0 10px 0 20px;
    }

    .bb2 {
      color: #000;
      font-size: 13px;
      margin-right: 14px;
    }
  }

  .m1 {
    font-size: 13px;
    color: #333;
    text-align: center;
    margin: 0px 0 30px;
  }

  .m2 {
    font-size: 13px;
    color: #878b97;
    text-align: center;
    margin: 0 0 12px;
  }

  .m3 {
    font-size: 14px;
    color: #333;
    text-align: center;
  }

  .m4 {
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #fff;
    background-image: linear-gradient(to bottom right, #36b4ea, #0996d3);
    border-radius: 3px;
    margin: 20px 0;
  }

  .m5 {
    font-size: 12px;
    color: #878b97;
    line-height: 18px;
  }
}

.cli {
  display: flex;
  height: 60px;
  align-items: center;
  background: #f2f2f2;
  border-radius: 4px;
  margin: 10px 20px 0px;

  &:last-child {
    margin-bottom: 10px;
  }

  img {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    margin-right: 20px;
    margin-left: 40px;
  }

  .cli2 {
    text-align: center;
    font-size: 15px;
  }
}

.m5 {
  font-size: 12px;
  color: #878b97;
  line-height: 18px;
}
</style>
